package com.boot.service;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.boot.bean.PictureVo;
import com.boot.dao.SevenInfoMapper;
import com.boot.entity.SevenInfo;
import com.boot.util.Byte2Image;
import com.boot.util.JudgeUtil;
import com.geccocrawler.gecco.downloader.DownloadException;
import com.geccocrawler.gecco.downloader.HttpClientDownloader;
import com.geccocrawler.gecco.request.HttpRequest;
import com.geccocrawler.gecco.response.HttpResponse;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class DownPic {

//	private final static String FILE_PATH = "F:\\个人\\爬虫\\SEVEN\\";
	private final static String FILE_PATH = "F:\\个人\\NEW_SEVEN\\";

	
    @Autowired  
    private SevenInfoMapper sevenInfoMapper; 
    private static DownPic downPic;  
  
    public void setUserInfo(SevenInfoMapper sevenInfoMappe) {  
        this.sevenInfoMapper = sevenInfoMapper;  
    }  
      
    @PostConstruct  
    public void init() {  
    	downPic = this;  
    	downPic.sevenInfoMapper = this.sevenInfoMapper;  
  
    }  
	
	/**
	 * 下载图片
	 *
	 * @author： WanG
	 * @日期：2017年4月30日 下午10:14:59
	 * @param pictureVo
	 * @param request
	 */
	public static void downPic(PictureVo pictureVo, HttpRequest request) {
		if (JudgeUtil.isPresent(pictureVo) && JudgeUtil.isPresent(pictureVo.getImgUrl())) {

			String imgUrl = bigPic(pictureVo.getImgUrl());
			String biaoti = biaoti(pictureVo.getBiaoti());
			String topic = pictureVo.getTopic();
			String picNum = getPicNum(imgUrl);

			StringBuilder sb = new StringBuilder();
			sb.append(FILE_PATH +topic+"\\"+ biaoti);

			// 检查下文件路径
			FilePath.ensure(sb.toString());

			HttpClientDownloader s = new HttpClientDownloader();

			request.setUrl(imgUrl);

			HttpResponse download = null;
			try {
				download = s.download(request, 3000);// 超时等待3秒
			} catch (DownloadException e) {
				e.printStackTrace();
			}

			ByteArrayInputStream raw = download.getRaw();
			BufferedImage img = null;
			try {
				img = ImageIO.read(raw);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			ByteArrayOutputStream out = new ByteArrayOutputStream();
			try {
				ImageIO.write(img, "jpg", out);
			} catch (IOException e) {
				e.printStackTrace();
			}
			byte[] b = out.toByteArray();

			sb.append("\\" + picNum + ".jpg");
			Byte2Image.byte2image(b, sb.toString());
			// d:\\drugcode.txt

			// 入库记录一下
			SevenInfo record = getSevenInfoRecord(imgUrl, biaoti, topic, picNum, img, sb.toString());
			downPic.sevenInfoMapper.insertSelective(record);
			
			
			log.info(download == null ? "无法下载" : download.toString());
		} else {
			// 如果为无效的,这里最好做点什么,记录下之类的
			
		}
	}

	private static SevenInfo getSevenInfoRecord(String imgUrl, String biaoti, String topic, String picNum, BufferedImage img, String path) {
		SevenInfo record = new SevenInfo();
		
		record.setUrl(imgUrl);
		record.setTopic(topic);
		record.setName(biaoti);
		record.setNum(picNum);
		record.setPath(path);
		record.setSize(Double.parseDouble(img.getWidth()+"")*Double.parseDouble(img.getHeight()+"")/1024);
		record.setRemark(img.getWidth() + " × " +img.getHeight());
		record.setCreateTime(new Date());
		
		return record;
	}

	private static String biaoti(String biaoti) {
		if (JudgeUtil.isPresent(biaoti)) {
			return biaoti;
		}
		Random random = new Random();
		return random.nextInt(4)+"";
	}


	/**
	 * 获取大图片
	 *
	 * @author： WanG
	 * @日期：2017年4月30日 下午10:14:27
	 * @param imgUrl
	 * @return
	 */
	private static String bigPic(String imgUrl) {
		if (JudgeUtil.isPresent(imgUrl)) {
			if (imgUrl.contains("small")) {
//				return imgUrl.replace("small", "large");
			}
		}
		return imgUrl;
	}

	/**
	 * 获取图片编号
	 *
	 * @author： WanG
	 * @日期：2017年4月30日 下午10:14:39
	 * @param imgUrl
	 * @return
	 */
	private static String getPicNum(String imgUrl) {
		if (JudgeUtil.isPresent(imgUrl)) {
			int lastIndexOf = imgUrl.lastIndexOf('/');
			int lastIndexOf2 = imgUrl.lastIndexOf('.');
			
			return imgUrl.substring(lastIndexOf+1, lastIndexOf2);
		}
		return "没有编号";
	}
}
